﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 平面法向量计算器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, EventArgs e)
        {
            try
            {
                Vector OA = GetPointVector(textP1.Text);
                Vector OB = GetPointVector(textP2.Text);
                Vector OC = GetPointVector(textP3.Text);
                Vector AB = new Vector(OA.X, OB.X, OA.Y, OB.Y, OA.Z, OB.Z);
                Vector AC = new Vector(OA.X, OC.X, OA.Y, OC.Y, OA.Z, OC.Z);

                Vector result = new Vector();

                //验证是否成平面
                if (AB.GetLength()==0 || AC.GetLength() == 0)
                {
                    throw new Exception("数据有误，无法构成平面！");
                }
                else
                {
                    double[] nums = new double[] {AB.X ,AB.Y ,AB.Z ,AC.X ,AC.Y ,AC.Z };
                    for (int i = 0; i < 3; i++)
                    {
                        if (nums[i] != 0 && nums[i+3] != 0) { 
                        double k = nums[i] / nums[i+3];
                            if (nums[0] == nums[3]*k && nums[1] == nums[4]*k && nums[2] == nums[5]*k) {
                                throw new Exception("数据有误，无法构成平面！");
                            }
                        }
                    }
                }

                // a = y1z2 - y2z1
                // b = z1x2 - z2x1
                // c = x1y2 - x2y1
                result.X = Math.Round((AB.Y * AC.Z)-(AC.Y * AB.Z),2);
                result.Y = Math.Round((AB.Z * AC.X)-(AC.Z * AB.X),2);
                result.Z = Math.Round((AB.X * AC.Y)-(AC.X * AB.Y),2);

                textResult.Text = result.X +","+result.Y +","+result.Z;

            }catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        //解析坐标点参数
        private double[] ParseParameters(string s)
        {
            string[] parameters = s.Split(new char[]{',','，'},StringSplitOptions.RemoveEmptyEntries);
            if(parameters.Length != 3)
            {
                throw new Exception("坐标参数不规范！");
            }
            double[] result = new double[3];
            for(int i = 0; i < parameters.Length; i++)
            {
                result[i] = Math.Round(double.Parse(parameters[i]),2);
            }
            return result;
        }
        //生成原点向量
        private Vector GetPointVector(string s)
        {
            double[] data = ParseParameters(s);
            Vector result = new Vector(data[0], data[1], data[2]);
            return result;
        }
        

        private void textP2_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
